import routeMap from "./router-map";
import Router from '@/router';

// 解析当前URL，返回路径和查询字符串
function getCurrentUrl() {
    const url = window.location.pathname + window.location.search;
    let [path, queryString = ''] = url.split('?');
    return { path, queryString };
}

// 构建完整的URL
function buildUrl(pagePath, queryString) {
    return queryString ? `${pagePath}?${queryString}` : pagePath;
}

// 匹配当前URL并导航
function matchAndNavigate() {
    const { path, queryString } = getCurrentUrl();
    let routeInfo = routeMap[path]; // 尝试直接匹配静态路由

    // 检查是否有动态路由匹配
    if (!routeInfo) {
        Object.keys(routeMap).forEach(pattern => {
            if (pattern.includes(':')) {
                const regex = new RegExp(`^${pattern.replace(/:[^\s/]+/g, '([\\w-]+)')}$`);
                const match = path.match(regex);
                if (match) {
                    // 正确复制路由信息并替换动态部分
                    routeInfo = { ...routeMap[pattern] };  // 复制对象，避免修改原始映射
                    routeInfo.path = routeInfo.path.replace(/:[^\s/]+/, match[1]);
                }
            }
        });
    }

    // 执行跳转
    if (routeInfo && routeInfo.path) {
        const finalUrl = buildUrl(routeInfo.path, queryString);
        Router.push(finalUrl)
        // window.location.href = finalUrl
    } else {
    }
}

export default matchAndNavigate;